package com.eight.cloud.admin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.eight.cloud.admin.common.constant.CacheKeyConstant;
import com.eight.cloud.admin.entity.RoleDeptEntity;
import com.eight.cloud.admin.entity.RoleEntity;
import com.eight.cloud.admin.mapper.RoleDeptMapper;
import com.eight.cloud.admin.mapper.RoleMapper;
import com.eight.cloud.admin.service.IDeptService;
import com.eight.cloud.admin.service.IRoleDeptService;
import com.eight.cloud.core.global.constant.DataScopeConstants;
import com.eight.cloud.core.global.model.LoginUser;
import com.eight.cloud.core.global.model.SysRole;
import com.eight.cloud.mybatisplus.entity.BaseEntity;
import com.eight.cloud.mybatisplus.service.BaseService;
import com.eight.cloud.redisson.model.TypedKey;
import com.eight.cloud.redisson.utils.RedisUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.eight.cloud.core.global.constant.NumConstant.ZERO;

/**
 * @ClassName: IRoleDeptServiceImpl
 * @Author: TXC
 * @Date: 2024-10-15 15:46
 **/
@Service
public class RoleDeptServiceImpl extends BaseService<RoleDeptMapper, RoleDeptEntity> implements IRoleDeptService {
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private IDeptService deptService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void flush(String roleId, List<String> deptIds) {
        List<RoleDeptEntity> roleDeptList =
                baseMapper.selectList(lambdaQueryWrapper().eq(RoleDeptEntity::getRoleId, roleId));
        Map<String, RoleDeptEntity> roleDeptMap =
                roleDeptList.stream().collect(Collectors.toMap(RoleDeptEntity::getDeptId, e -> e));
        deptIds.forEach(deptId -> {
            RoleDeptEntity roleDept = roleDeptMap.get(deptId);
            if (ObjectUtil.isNotNull(roleDept)) {
                roleDeptMap.remove(deptId);
            } else {
                RoleDeptEntity roleDeptEntity = new RoleDeptEntity();
                roleDeptEntity.setRoleId(roleId);
                roleDeptEntity.setDeptId(deptId);
                roleDeptEntity.insert();
            }
        });
        roleDeptMap.forEach((k, v) -> v.deleteById());
    }

    @Override
    public List<String> getDeptIds(String roleId) {
        String cacheKey = CacheKeyConstant.generateKey(CacheKeyConstant.ADMIN_ROLE_DEPT, roleId);
        return redisUtils.cacheOrFetch(TypedKey.<List<String>>builder().key(cacheKey).type(new TypeReference<>() {}).build()
                , () -> {
                    RoleEntity role = roleMapper.selectById(roleId);
                    if (DataScopeConstants.DATA_SCOPE_CUSTOM.equals(role.getDataScope())) {
                        return baseMapper.selectList(lambdaQueryWrapper().eq(RoleDeptEntity::getRoleId,
                                roleId)).stream().map(BaseEntity::getUuid).collect(Collectors.toList());
                    } else {
                        return null;
                    }
                });
    }

    @Override
    public List<String> getDeptIds(SysRole role, LoginUser loginUser) {
        if (DataScopeConstants.DATA_SCOPE_CUSTOM.equals(role.getDataScope())) {
            return getDeptIds(role.getUuid());
        } else if (DataScopeConstants.DATA_SCOPE_DEPT.equals(role.getDataScope())) {
            return Collections.singletonList(loginUser.getDeptId());
        } else if (DataScopeConstants.DATA_SCOPE_DEPT_AND_CHILD.equals(role.getDataScope())) {
            return deptService.getDeptAndChild(loginUser.getDeptId()).get(ZERO).obtainGetSubNode()
                    .stream().map(v -> (String) v).collect(Collectors.toList());
        } else {
            return Collections.emptyList();
        }
    }
}
